package cn.kbyue.asyncdemo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.WebAsyncTask;

import java.util.concurrent.Callable;

@Slf4j
@RestController
@RequestMapping("/future")
public class FutureController {

    @GetMapping("/call")
    public Callable<String> testAsync() throws InterruptedException {
        log.info("主线程开始=====>"+ Thread.currentThread().getName());
        Callable<String> callable = () -> {
            log.info("异步线程开始=====>" + Thread.currentThread().getName());
            Thread.sleep(10000);
            log.info("异步线程结束=====>" + Thread.currentThread().getName());
            return "success";
        };
        log.info("主线程结束=====>"+ Thread.currentThread().getName());
        return callable;
    }

    @GetMapping("/async")
    public WebAsyncTask<String> asyncTask(){
        // 1000 为超时设置
        WebAsyncTask<String> webAsyncTask = new WebAsyncTask<>(1000, () -> {
            //业务逻辑处理
            Thread.sleep(5000);
            return "username:xxxx";
        });
        webAsyncTask.onCompletion(() -> System.out.println("调用完成"));
        webAsyncTask.onTimeout(() -> {
            System.out.println("业务处理超时");
            return "<h1>Time Out</h1>";
        });
        return webAsyncTask;
    }


}
